<template>
  <a-row :gutter="10">
    <a-col :md="12" :sm="24" style="height:320px; padding:0;">
      <a-card :bordered="false">
        <!-- <a-alert type="info" :showIcon="true" style="margin: 0px 0">
          <div slot="message">
            当前选择：<span v-if="this.currSelected">{{ getCurrSelectedTitle() }}</span>
            <a v-if="this.currSelected" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
          </div>
        </a-alert> -->
        <!-- 政府部门树 -->
        <a-col class="department-tree" style="height:320px;">
          <span style="user-select: none">
            <a-spin class="tree" :style="{ overflow: loading ? 'hidden' : 'auto' }" :spinning="loading">
              <a-tree :selectedKeys="selectedKeys" :replaceFields="{ title: 'name', key: 'id' }" :treeData="allTreeData" :load-data="onLoadData" :expandedKeys="iExpandedKeys" showIcon @expand="onExpand" :autoExpandParent="autoExpandParent" @select="onSelect">
                <!-- children: 'childList' -->
                <a-icon slot="layer" type="file" />
              </a-tree>
            </a-spin>
          </span>
        </a-col>
      </a-card>
    </a-col>
    <a-col :md="12" :sm="24" style="height:380px;">
      <a-card :bordered="false">
        <a-empty v-show="!(selectedKeys.length)">
          <span slot="description"> 请先选择一个分组! </span>
        </a-empty>
        <AddressBookTable v-show="selectedKeys.length" ref="addressBookTable" v-bind="$attrs" v-on="$listeners"></AddressBookTable>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import AddressBookTable from './ScSubjectMeetingAddressTable.vue'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'AddressBookManage',
  components: {
    AddressBookTable
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      memberId: '',
      disableMixinCreated: true,
      allTreeData: [],
      queryParam: {},
      iExpandedKeys: [],
      mlfz: [], // 人员目录分组
      // departName: '政府市部门',
      // outName: '外部联系人',
      // expertName: '专家库',
      allTreeKeys: [],
      selectType: 0, // 判断当前选中的类型,1是部门 3是专家库 2是外部联系人
      loading: false,
      autoExpandParent: true,
      disable: true,
      disableSubmit: false,
      selectedKeys: [],
      currSelected: null,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      url: {
        // delete: '/subject/scSubjectLayerInfo/delete',
        // deleteGroup: '/subject/scSubjectLayerGroup/delete',
        // edit: '/sys/sysDepart/edit',
        // deleteBatch: '/sys/sysDepart/deleteBatch',
        // list: '/subject/scSubjectContactsBook/queryIndexCatalogue',
        // queryList: '/subject/scSubjectLayerGroup/getLeftDirectoryByGroupName',
        // groupDetail: '/subject/scSubjectContactsBookRel/list'
        deleteGroup: '/subject/scSubjectContactsBook/delete',
        list: '/subject/scSubjectContactsBook/listRootByType',
        queryList: '/subject/scSubjectLayerGroup/getLeftDirectoryByGroupName',
        groupDetail: '/subject/scSubjectContactsBookRel/list',
        getChildList: '/subject/scSubjectContactsBook/getChildList'
      }
    }
  },
  computed: {
    // 判断是否显示添加下级、编辑按钮
    isShow() {
      return (this.selectType === '3' && this.currSelected.name !== '未分配组') || this.selectType === '2'
    }
  },
  created() {
    this.getType()// 先获取人员目录分组
    this.loadTree()
  },
  methods: {
    getType() {
      getAction('/sys/dict/getDictItems/rymllx').then(res => {
        if (res.success) {
          this.mlfz = res.result
        }
      })
    },
    loadTree() {
      this.loading = true
      this.allTreeData = []
      this.allTreeKeys = []
      this.iExpandedKeys = []
      var that = this
      getAction(this.url.list)
        .then((res) => {
          if (res.success) {
            var result = res.result
            for (var item of result) {
              var name = item.type_dictText
              // 只加到专家父级，专家里加未关联的菜单
              if (item.type === '3' && !item.id && item.bookList) {
                var unRelationData = {
                  name: '未分配组',
                  type: '3',
                  id: 'unrelation',
                  isLeaf: true
                }
                item.bookList.push(unRelationData)
              }
              var data = {
                name: name,
                id: item.type === '1' ? 'depart' : item.type === '2' ? 'out' : 'expert',
                disabled: true,
                children: item.bookList
              }
              that.allTreeData.push(data)
              that.setThisExpandedKeys(data)
              that.getAllKeys(data)
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    submitCallback() {
      console.log('重新加载数据')
      this.loadTree()
    },
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        setTimeout(() => {
          getAction(this.url.getChildList, { pid: treeNode.dataRef.id }).then(res => {
            if (res.success) {
              res.result.forEach((item) => {
                if (this.iExpandedKeys.filter((id) => id == item.Id).length > 0) {
                  this.iExpandedKeys.push(item.Id)
                }
                var childrenData = res.result
                treeNode.dataRef.children = childrenData
                this.allTreeData = [...this.allTreeData]
              })
            }
          })
          resolve()
        }, 1)
      })
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.id)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    getAllKeys(node) {
      this.allTreeKeys.push(node.id)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    // 获取分组详细信息
    getGroupDetail(record) {
      this.currSelected = record
      this.$refs.addressBookTable.open(this.currSelected)
    },
    // 获取分组详细信息
    createGroup(num) {
      if (num == 1) {
        this.$refs.addressGroupModal.add()
        this.$refs.addressGroupModal.isSub = false
        this.$refs.addressGroupModal.title = '新建分组'
      } else if (num == 2) {
        this.$refs.addressGroupModal.disableSubmit = false
        this.$refs.addressGroupModal.title = '编辑分组'
        this.$refs.addressGroupModal.edit(this.currSelected)
      } else if (num == 3) {
        this.$refs.addressGroupModal.title = '分组详情'
        this.$refs.addressGroupModal.disableSubmit = true
        this.$refs.addressGroupModal.edit(this.currSelected)
      } else {
        this.$refs.addressGroupModal.isSub = true
        this.$refs.addressGroupModal.title = '添加下级'
        this.$refs.addressGroupModal.disableSubmit = false
        this.$refs.addressGroupModal.add(this.currSelected)
      }
    },
    onSearch(value) {
      const that = this
      if (value) {
        getAction(this.url.queryList, { name: value }).then((res) => {
          if (res.success) {
            that.treeData = []
            const records = res.result
            for (let i = 0; i < records.length; i++) {
              const temp = records[i]
              that.treeData.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    onSelect(selectedKeys, e) {
      const record = e.node.dataRef
      // 代表是最底层
      this.getGroupDetail(record)
      this.currSelected = record
      this.selectedKeys = [record.id]
      this.selectType = this.currSelected.type
    },
    getCurrSelectedTitle() {
      return this.currSelected.name || this.currSelected.layerName
    },
    onClearSelected() {
      this.currSelected = null
      this.form.resetFields()
      this.selectedKeys = []
      this.selectType = 0
    },
    handleDelete() {
      var that = this
      const key = this.currSelected.id
      if (!key) {
        this.$message.warning('请先选中删除的内容！')
        return false
      }
      console.log('删除id:', key)
      this.$confirm({
        title: '确认删除',
        content: '确定要删除么?',
        onOk() {
          deleteAction(that.url.deleteGroup, { id: key }).then(resp => {
            if (resp.success) {
              that.$message.success('删除成功!')
              that.loadTree()
              that.onClearSelected()
            } else {
              that.$message.warning('删除失败!')
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 10px !important;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0;
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

#app .desktop {
  height: auto !important;
}

.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

.department-tree {
  margin-top: 5px;
  width: 100%;
  height: 200px;
  overflow: auto;
  ::v-deep .ant-spin-nested-loading {
    position: initial;
  }
}

.basicInfo-card {
  ::v-deep .ant-card-body {
    height: 650px;
    overflow: auto;
  }
}

.tree {
  height: calc(100% - 4px);
  margin: 2px 0;
}
</style>
